import torch
import os
import numpy as np
from transformers import set_seed

def set_random_seed(seed=42):
    """设置随机种子，保证结果可复现"""
    set_seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)
        torch.backends.cudnn.deterministic = True
        torch.backends.cudnn.benchmark = False

def get_device():
    """获取可用设备"""
    return torch.device("cuda" if torch.cuda.is_available() else "cpu")

def model_summary(model):
    """打印模型摘要信息"""
    print(model)
    print(f"模型参数总数: {sum(p.numel() for p in model.parameters()):,}")
    print(f"可训练参数总数: {sum(p.numel() for p in model.parameters() if p.requires_grad):,}")

def save_model_config(config, save_path):
    """保存模型配置"""
    os.makedirs(os.path.dirname(save_path), exist_ok=True)
    with open(save_path, 'w', encoding='utf-8') as f:
        for key, value in config.items():
            f.write(f"{key}: {value}\n")